'''
This file handles all the request related to in and out operation
'''

import os

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.db import djangoforms

import django
from django import http

#local import
from form import StatisticForm
from util import respond
from dao import LocalUsers

def index(request):
  user = users.GetCurrentUser()
  statistics = db.GqlQuery('SELECT * FROM Statistic ORDER BY addDate DESC')
  return respond(request, user, 'statistic/list', {'statistics': statistics})

def edit(request, statistic_id):
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit a statistic')

  statistic = None
  if statistic_id:
    statistic = Statistic.get(db.Key.from_path(Statistic.kind(), int(statistic_id)))
    if statistic is None:
      return http.HttpResponseNotFound('No statistic exists with that key (%r)' %statistic_id)

  form = StatisticForm(data=request.POST or None, instance=statistic)

  if not request.POST:
    return respond(request, user, 'statistic/modify', {'form': form, 'statistic': statistic})

  errors = form.errors
  if not errors:
    try:
      statistic = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'statistic/modify', {'form': form, 'statistic': statistic})

  localuser.put()

  return http.HttpResponseRedirect('/statistic')

def new(request):
  return edit(request, None)

def delete(request, statistic_id):
    if statistic_id:
        statistic = Statistic.get(db.Key.from_path(Statistic.kind(), int(statistic_id)))
        if statistic is None:
            return http.HttpResponseNotFound('No user exists with that key (%r)' %statistic_id)
        else:
            statistic.delete()
    
    return http.HttpResponseRedirect('/statistic')
